#!/bin/bash
set -e

BRANCH_PATH="/frzr_root/source"
BRANCH_CONF="/frzr_root/os-branch.conf"
REPO="SkorionOS/skorionos"
OTHER_SOURCE=""

LOCAL_LANG_FILE="/etc/locale.conf"

if [[ -f "$LOCAL_LANG_FILE" ]]; then
  source "$LOCAL_LANG_FILE"
fi

if [[ -f "$BRANCH_CONF" ]]; then
  source "$BRANCH_CONF"
fi

BRANCH_FLG="${BRANCH_PREFIX:-}"
DESKTOP="${DESKTOP:-}"
REPO_ADDON_FLAG="${REPO_ADDON_PREFIX:-}"
NV_BRANCH_FLG="${NV_BRANCH_PREFIX:-}"

VALID_BRANCHES=(
  "rel"
  "beta"
  "main"
)

DESKTOP_LIST=(
  "gnome"
  "kde"
  "hyprland"
  # "cinnamon"
  # "cosmic"
)

VALID_ADDON_FLAGS=(
  "nv"
  "core"
  "full"
)

# function load_addon_config() {
#   # 如果配置文件中有新格式，优先使用
#   if [[ -n "$REPO_ADDON_FLAG" ]]; then
#     return
#   fi

#   # 兼容旧格式：从 NV_BRANCH_FLG 转换到 REPO_ADDON_FLAG
#   if [[ "$NV_BRANCH_FLG" == "1" ]]; then
#     REPO_ADDON_FLAG="nv"
#   else
#     REPO_ADDON_FLAG=""
#   fi
# }

# function sync_ui_from_addon() {
#   if [[ "$REPO_ADDON_FLAG" == "nv" ]]; then
#     NV_BRANCH_FLG="1"
#   else
#     NV_BRANCH_FLG="0"
#   fi
# }

function parse_branch_conf() {
  local source_file=$BRANCH_PATH

  if [[ ! -f "$source_file" ]]; then
    echo >&2 "Error: $source_file not found"
    return 1
  fi

  branch_repo=$(sed -n 's/^\(honjow\|3003n\|SkorionOS\)\/skorionos://p' "$source_file")
  if [[ -z "$branch_repo" ]]; then
    echo >&2 "Error: No branch repo found in $source_file"
    OTHER_SOURCE=$(cat "$source_file")
    return 1
  fi

  branch_type=$(echo "$branch_repo" | cut -d ':' -f 1)
  build_type=$(echo "$branch_repo" | cut -d ':' -f 2)

  build_desktop=${build_type%%-*}
  if [[ "$build_type" == *-* ]]; then
    build_addon=${build_type#*-}
  else
    build_addon=""
  fi

  # echo "branch_type: $branch_type, build_type: $build_type, build_desktop: $build_desktop, build_addon: $build_addon" >&2

  case "$branch_type" in
  "stable")
    BRANCH_FLG="rel"
    ;;
  "testing")
    BRANCH_FLG="beta"
    ;;
  "unstable")
    BRANCH_FLG="main"
    ;;
  *)
    BRANCH_FLG="rel"
    ;;
  esac

  case "$build_desktop" in
  "gnome")
    DESKTOP="gnome"
    ;;
  "kde")
    DESKTOP="kde"
    ;;
  "cosmic")
    DESKTOP="cosmic"
    ;;
  "cinnamon")
    DESKTOP="cinnamon"
    ;;
  "hyprland")
    DESKTOP="hyprland"
    ;;
  *)
    DESKTOP="gnome"
    ;;
  esac

  # Check if build_addon is in VALID_ADDON_FLAGS
  if [[ "$build_addon" == "none" ]]; then
    REPO_ADDON_FLAG=""
  elif [[ " ${VALID_ADDON_FLAGS[*]} " == *" $build_addon "* ]]; then
    REPO_ADDON_FLAG="$build_addon"
  else
    [[ -n "$build_addon" ]] && echo "not supported build_addon: $build_addon" >&2
    REPO_ADDON_FLAG=""
  fi
}

function is_supported_nv_branch() {
  local desktop="$1"

  case "$desktop" in
  "gnome")
    return 0
    ;;
  "kde")
    return 0
    ;;
  esac

  return 1
}

function generate_branch_list() {
  local branch_type="$1"
  local desktop="$2"
  local repo_addon_flag="$3"

  echo "generate_branch_list >> branch_type: $branch_type, desktop: $desktop, repo_addon_flag: $repo_addon_flag" >&2

  branch_list=("${VALID_BRANCHES[@]}")

  desktop_label=$(generate_desktop_label)
  for d in "${DESKTOP_LIST[@]}"; do
    if [[ "$desktop" == "$d" ]]; then
      branch_list+=("$desktop_label $desktop ✔")
    else
      branch_list+=("$desktop_label $d")
    fi
  done

  # nvidia_label=$(generate_nvidia_label)
  # if [[ "$nv_branch_flg" == "1" ]]; then
  #   branch_list+=("$nvidia_label ✔")
  # else
  #   branch_list+=("$nvidia_label ✘")
  # fi

  addon_label=$(generate_addon_label)
  for f in "${VALID_ADDON_FLAGS[@]}"; do
    if [[ "$repo_addon_flag" == "$f" ]]; then
      branch_list+=("$addon_label $f ✔")
    else
      branch_list+=("$addon_label $f")
    fi
  done

  for item in "${branch_list[@]}"; do
    echo "$item"
  done
}

function generate_desktop_label() {
  case "$LANG" in
  "zh_CN.UTF-8")
    echo "桌面:"
    ;;
  *)
    echo "Desktop:"
    ;;
  esac
}

function generate_addon_label() {
  case "$LANG" in
  "zh_CN.UTF-8")
    echo "标识:"
    ;;
  *)
    echo "Flag:"
    ;;
  esac
}

function generate_nvidia_label() {
  case "$LANG" in
  "zh_CN.UTF-8")
    echo "包含 NVIDIA"
    ;;
  *)
    echo "With NVIDIA"
    ;;
  esac
}

function save_branch_conf() {
  local set_tag="$*"

  addon_label=$(generate_addon_label)

  case "$set_tag" in
  "$addon_label"*" ✔")
    REPO_ADDON_FLAG=""
    ;;
  "$addon_label"*)
    REPO_ADDON_FLAG=$(echo "$set_tag" | cut -d ' ' -f 2)
    ;;
  *)
    if [[ "$set_tag" == *"✔" ]]; then
      return 0
    else
      for d in "${DESKTOP_LIST[@]}"; do
        if [[ "$set_tag" == *"$d"* ]]; then
          DESKTOP="$d"
          break
        fi
      done
      for b in "${VALID_BRANCHES[@]}"; do
        if [[ "$set_tag" == "$b" ]]; then
          BRANCH_FLG="$b"
          break
        fi
      done
    fi
    ;;
  esac

  # 同步到新变量
  # if [[ "$NV_BRANCH_FLG" == "1" ]]; then
  #   REPO_ADDON_FLAG="nv"
  # fi

  # echo "save branch conf"
  # echo "BRANCH_FLG=$BRANCH_FLG"
  # echo "DESKTOP=$DESKTOP"
  # echo "REPO_ADDON_FLAG=$REPO_ADDON_FLAG"

  (
    echo "BRANCH_FLG=$BRANCH_FLG"
    echo "DESKTOP=$DESKTOP"
    echo "REPO_ADDON_FLAG=$REPO_ADDON_FLAG"
  ) >"$BRANCH_CONF"
}

function get_repo_from_branch_conf() {
  local branch_flg="$1"
  local desktop="$2"
  local repo_addon_flag="$3"

  # echo "get_repo_from_branch_conf >> branch_flg: $branch_flg, desktop: $desktop, repo_addon_flag: $repo_addon_flag" >&2

  repo_branch="stable"
  case "$branch_flg" in
  "rel")
    repo_branch="stable"
    ;;
  "beta")
    repo_branch="testing"
    ;;
  "main")
    repo_branch="unstable"
    ;;
  *)
    repo_branch="stable"
    ;;
  esac

  repo_addon=""
  if [[ -n "$repo_addon_flag" ]]; then
    repo_addon="-$repo_addon_flag"
  fi

  if [[ -z "$desktop" ]]; then
    desktop="gnome"
  fi

  echo "$REPO:$repo_branch:$desktop$repo_addon"
}

parse_branch_conf || echo >&2 "Error: Failed to parse branch conf"

echo "BRANCH_FLG=$BRANCH_FLG, DESKTOP=$DESKTOP, REPO_ADDON_FLAG=$REPO_ADDON_FLAG" >&2

# 处理配置文件兼容性和UI同步
# load_addon_config
# sync_ui_from_addon

case "$1" in
"-c")
  if [[ -n "$OTHER_SOURCE" ]]; then
    echo "$OTHER_SOURCE"
    exit 0
  fi

  real_branch=$(sed -n 's/^\(honjow\|3003n\|SkorionOS\)\/skorionos://p' "$BRANCH_PATH" 2>/dev/null)
  if [[ -z "$BRANCH_FLG" && -z "$DESKTOP" ]]; then
    echo >&2 "Warning: Unrecognized currently selected branch name '$real_branch', updates may not succeed."
    echo "$real_branch"
    exit 0
  fi

  echo "$BRANCH_FLG"
  ;;
"-l")
  if [[ -n "$OTHER_SOURCE" ]]; then
    echo "$OTHER_SOURCE"
  fi

  mapfile -t show_branch_list < <(generate_branch_list "$BRANCH_FLG" "$DESKTOP" "$REPO_ADDON_FLAG")
  for b in "${show_branch_list[@]}"; do
    echo "$b"
  done
  exit 0
  ;;
*)
  # 所有参数都作为 set_tag 传递给 save_branch_conf
  save_branch_conf "$@"
  repo=$(get_repo_from_branch_conf "$BRANCH_FLG" "$DESKTOP" "$REPO_ADDON_FLAG")
  echo "Switching to [$repo]"
  echo "$repo" >"$BRANCH_PATH"

  if [ $# -eq 0 ]; then
    mapfile -t branch_list < <(generate_branch_list "$BRANCH_FLG" "$DESKTOP" "$REPO_ADDON_FLAG")
    sep=" | "
    printf -v result "%s$sep" "${branch_list[@]}"
    result="${result%"$sep"}"
    echo "Usage: steamos-select-branch <-$result>" 1>&2
  fi

  exit 0
  ;;
esac
